<template>
	<view class="wrapper order">
		<view class="order-tab">
			<u-tabs
				lineColor="#e3230e"
				lineWidth="90rpx"
				:current="current"
				:itemStyle="{
					height: '80rpx',
					fontSize: '32rpx'
				}"
				:inactiveStyle="{
					color: '#333333'
				}"
				:activeStyle="{
					color: '#e3230e',
					fontWeight: '600'
				}"
				:scrollable="false"
				:list="tabList"
				@click="clickTab"></u-tabs>
		</view>
		<view class="order-content">
			<view class="order-list">
				<view class="order-item" v-for="(item, index) in tableList" :key="item.id">
					<view class="order-item-top order-item-main">
						<view class="order-item-top-l main-flex">
							<view class="order-item-number main-flex">
								<text>订单号：{{item.orderNumber}}</text>
								<image class="order-item-icon" @click.stop="copyText(item.orderNumber)" src="/static/images/icon/copy.png"></image>
							</view>
							<view class="order-item-status" :class="`status${item.status}`">{{arrText(orderStatusList, item.status)}}</view>
						</view>
						<view class="order-item-time">下单时间：{{item.createTime}}</view>
					</view>
					<view class="order-item-center">
						<view class="order-item-box" @click="goOrder(item)">
							<view class="order-item-goods">
								<scroll-view
									scroll-x
									class="order-item-goods-box"
									scroll-with-animation
									:show-scrollbar="false">
									<view class="order-item-goods-list main-flex">
										<view class="order-item-goods-item" v-for="child in item.productList" :key="child">
											<view class="order-item-goods-item-img">
												<image class="order-item-goods-item-img-url" :src="imgUrl(child.productImg)"></image>
											</view>
											<view class="order-item-goods-count main-flex">
												数量：<text class="order-item-goods-count-text">{{child.number}}</text>
											</view>
										</view>
										<view class="order-item-goods-line"></view>
									</view>
								</scroll-view>
								<view class="order-item-goods-total main-flex">
									<view class="order-item-goods-money">￥{{item.actualPrice}}</view>
									<!-- <view class="order-item-goods-count">
										共<text class="order-item-goods-count-text">{{item.orderCount}}</text>件
									</view> -->
									<view class="order-item-more main-flex" @click.stop="showChild(index, item)" v-if="item?.children && item.children.length > 0">
										<uni-icons class="order-item-more-icon" :class="item.showChild ? 'order-item-up' : ''" type="down" size="20" color="#e3230e"></uni-icons>
									</view>
								</view>
							</view>
						</view>
						
						<view class="order-item-list" :style="{ height: item.showChild ? `${272 * item.children.length}rpx` : '0rpx' }">
							<view class="order-item-box" v-for="(child, childIndex) in item.children" :key ="child.id">
								<view class="order-item-top main-flex">
									<view class="order-item-number main-flex">
										<text>订单号：{{child.orderNumber}}</text>
										<image class="order-item-icon" @click.stop="copyText(child.orderNumber)" src="/static/images/icon/copy.png"></image>
									</view>
									<view class="order-item-status" :class="`order-status${child.status}`">{{arrText(orderStatusList, child.status)}}</view>
								</view>
								<view class="order-item-goods" @click="goOrder(item)">
									<scroll-view
										scroll-x
										class="order-item-goods-box"
										scroll-with-animation
										:show-scrollbar="false">
										<view class="order-item-goods-list main-flex">
											<view class="order-item-goods-item" v-for="childItem in child.productList" :key="childItem">
												<view class="order-item-goods-item-img">
													<image class="order-item-goods-item-img-url" :src="imgUrl(childItem.productImg)"></image>
												</view>
												<view class="order-item-goods-count main-flex">
													数量：<text class="order-item-goods-count-text">{{childItem.number}}</text>
												</view>
											</view>
											<view class="order-item-goods-line"></view>
										</view>
									</scroll-view>
									<view class="order-item-goods-total main-flex">
										<view class="order-item-goods-money">￥{{child.actualPrice}}</view>
										<view class="order-item-goods-btns main-flex">
											<view @click.stop="cancelOrder(child)" class="order-item-goods-btns-item order-item-goods-btns-item1" v-if="child.status === 0">取消订单</view>
											<view @click.stop="goExpress(child)" class="order-item-goods-btns-item order-item-goods-btns-item2" v-if="child.status === 2">查看物流</view>
											<view @click.stop="confirmReceipt(child)" class="order-item-goods-btns-item order-item-goods-btns-item3"  v-if="child.status === 2">确认收货</view>
										</view>
									</view>
								</view>
							</view>
						</view>
						
					</view>
					<view class="order-item-bottom main-flex">
						<view class="order-item-money">合计：￥{{item.orderMoney}}</view>
						<view class="order-item-btns main-flex-item main-flex">
							<button @click="cancelOrder(item)" class="ty-button ty-button-plain-cancel order-item-btn" v-if="item.status === 0">取消订单</button>
							<button @click="payOrder(item)" class="ty-button ty-button-plain-confirm order-item-btn" v-if="item.status === 0">立即付款</button>
							<button @click="goExpress(item)" class="ty-button ty-button-plain-warning order-item-btn" v-if="item.status === 2">查看物流</button>
							<button @click="confirmReceipt(item)" class="ty-button ty-button-plain-confirm order-item-btn" v-if="item.status === 2">确认收货</button>
							<button @click="goService" class="ty-button ty-button-plain-confirm order-item-btn service">
								<image class="order-item-btn-icon" src="/static/images/icon/weixin.png"></image>
								<text>联系售后</text>
							</button>
						</view>
					</view>
				</view>
				
				<!--加载-->
				<view
					v-if="isNull"
					class="null main-flex">
					<u-empty text="~ 没有订单数据哟 ~" icon="/static/images/null.png"></u-empty>
					<view class="null-btn" @click="goBuy">去逛逛</view>
				</view>
				<view
					v-else
					class="more main-flex">
					<uni-load-more :status="status" />
				</view>
				
			</view>
		</view>
		<pay
			:showPay="showPay"
			:order="orderInfo"
			@success="successPay"
			@close="closePay"></pay>
	</view>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { onReady, onLoad, onReachBottom, onShow, onHide, onUnload } from '@dcloudio/uni-app';
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { throttle, debounce } from '@/uni_modules/uview-plus'
import modal from '@/plugins/modal'
import { orderMainList, orderCancel, orderConfirmReceipt } from "@/api/app_api/order"
import { orderStatusList } from '@/utils/config'
import { arrText, serviceWeixin } from '@/utils/ty'
import { getMpLogin } from '@/utils/login.js'
import { Decimal } from 'decimal.js'

	const userStore = useUserStore()
	const setStore = useSetStore()
	
	// tabs
	const current = ref(0)
	const tabList = ref([
		{ status: '', name: '全部', tIndex: 0 },
		{ status: 0, name: '待付款', tIndex: 1 },
		{ status: 1, name: '待发货', tIndex: 2 },
		{ status: 2, name: '待收货', tIndex: 3 },
		{ status: 6, name: '已完成', tIndex: 4 }
	])
	const clickTab = (e) => {
		type.value = e.status
		searchFirst()
	}
	
	// 列表查询
	const type = ref('')
	const tableList = ref([])
	const isLoading = ref(false)
	const status = ref('more')
	const isNull = ref(false)
	const pageNum = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	
	const searchFirst = () => {
		if (!getMpLogin()) {
			return false
		}
		tableList.value = []
		status.value = 'loading'
		isNull.value = false
		pageNum.value = 1
		total.value = 0
		getList()
	}
	
	// 触底查询
	onReachBottom(() => {
		if(status.value == 'no-more') return false;
		pageNum.value += 1
		status.value = 'loading'
		getList()
	})
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			isAsc: 'desc'
		}
		if (type.value || type.value == 0) {
			params.status = type.value
		}
		isLoading.value = true
		// uni.showLoading({
		// 	title: '数据加载中...'
		// })
		orderMainList(params).then(res => {
			tableList.value = tableList.value.concat(res.data.map(item => {
				const orderMoney = item.children.reduce((prev, cur, index, arr)=> {
					return Decimal(prev).add(Decimal(cur.actualPrice)).toNumber()
				}, 0)
				return {
					...item,
					orderMoney: Decimal(orderMoney).add(Decimal(item.actualPrice)).toNumber()
				}
			}) || [])
			status.value = res.data.length === pageSize.value ? 'loading' : 'no-more'
			total.value = res.allNumber
			isNull.value = res.allNumber === 0 && pageNum.value === 1
			isLoading.value = false
			// uni.hideLoading()
		}).catch(() => {
			isLoading.value = false
			isNull.value = false
			// uni.hideLoading()
		})
	}
	
	const goodsCount = (item) => {
		return item?.productList.reduce((prev, cur, index, arr)=> {
				return prev + cur.number
			}, 0)
	}
	
	// 查看更多
	const showChild = (index, row) => {
		if (tableList.value[index]?.showChild) {
			tableList.value[index].showChild = !tableList.value[index].showChild
		} else {
			tableList.value[index].showChild = true
		}
	}
	
	// 查看订单
	const goOrder = (item) => {
		const childIds = item.children.map(item => item.id)
		uni.navigateTo({
			url: childIds.length > 0 ? `/pages/order/detail2?id=${item.id},${childIds.join(',')}` : `/pages/order/detail?id=${item.id}`
		})
	}
	
	// 去看看
	const goBuy = () => {
		uni.switchTab({
			url: '/pages/category/category'
		})
	}
	
	// 取消订单
	const cancelOrder = (item) => {
		uni.showModal({
			title: '取消订单',
			content: '确认取消此订单吗？',
			success: function (res) {
				if (res.confirm) {
					cancelOrderFun(item.id)
				} else if (res.cancel) {
					
				}
			}
		})
	}
	const isCancel = ref(false)
	const cancelOrderFun = (id) => {
		if (isCancel.value) return false
		isCancel.value = true
		orderCancel({
			id
		}).then(res => {
			uni.$u.toast('订单已取消')
			searchFirst()
			isCancel.value = false
		}).catch(() => {
			isCancel.value = false
		})
	}
	
	// 确认收货
	const confirmReceipt = (item) => {
		uni.showModal({
			title: '确认收货',
			content: '确认收到货物了吗？',
			success: function (res) {
				if (res.confirm) {
					confirmReceiptFun(item.id)
				} else if (res.cancel) {
					
				}
			}
		})
	}
	const isConfirmReceipt = ref(false)
	const confirmReceiptFun = (id) => {
		if (isConfirmReceipt.value) return false
		isConfirmReceipt.value = true
		orderConfirmReceipt({
			id
		}).then(res => {
			uni.$u.toast('订单已收货')
			isConfirmReceipt.value = false
			searchFirst()
		}).catch(() => {
			isConfirmReceipt.value = false
		})
	}
	
	// 客服
	const goService = () => {
		serviceWeixin()
	}
	
	// 查看物流
	const goExpress = (item) => {
		uni.navigateTo({
			url: `/pages/order/express?id=${item.id}`
		})
	}
	
	onLoad((option) => {
		if (option.status) {
			const filterStatus = tabList.value.find(item => item.status == option.status)
			type.value = filterStatus.status
			current.value = filterStatus?.tIndex || 0
		}
		searchFirst()
		uni.$on('refresh', () => {
			searchFirst()
		})
	})
	
	onUnload(() => {
		uni.$off('refresh')
	})
	
	// 支付相关
	const isPayOrder = ref(false)
	const showPay = ref(false)
	const orderInfo = ref({})
	const payOrder = (item) => {
		showPay.value = true
		orderInfo.value = item
	}
	const closePay = () => {
		showPay.value = false
		orderInfo.value = {}
	}
	const successPay = () => {
		// uni.navigateTo({
		// 	url: `/pages/order/success?orderId=${order.orderId}&money=${order.actualPrice}&name=${order.payName}&orderNumber=${order.orderNumber}`
		// })
		searchFirst()
	}
	
	watch(() => userStore.user.id, (nval, oval) => {
		if (nval) {
			searchFirst()
		}
	})
	
</script>

<style lang="scss" scoped>
	.order {
		&-tab {
			position: fixed;
			height: 80rpx;
			width: 100%;
			left: 0;
			background-color: #ffffff;
			z-index: 10;
		}
		&-content {
			padding: 100rpx 20rpx 20rpx;
		}
		&-list {
		}
		&-item {
			background-color: #ffffff;
			border-radius: 20rpx;
			padding: 0 20rpx;
			&+.order-item {
				margin-top: 20rpx;
			}
			&-top {
				height: 72rpx;
			}
			&-main {
				flex-direction: column;
				padding: 12rpx 0;
			}
			&-time {
				font-size: 24rpx;
			}
			&-number {
				font-size: 24rpx;
			}
			&-icon {
				width: 32rpx;
				height: 32rpx;
				margin-left: 20rpx;
			}
			&-status {
				margin-left: auto;
				font-size: 24rpx;
			}
			&-money {
				font-size: 24rpx;
				color: $primary-color;
			}
			.status5 {
				color: $text-light;
			}
			&-goods {
				position: relative;
				padding: 20rpx 100rpx 20rpx 0;
				&-box {
					white-space: nowrap;
				}
				&-item {
					width: 120rpx;
					height: 160rpx;
					margin-right: 20rpx;
					&-img {
						width: 120rpx;
						height: 120rpx;
						font-size: 0;
						&-url {
							width: 100%;
							height: 100%;
						}
					}
				}
				&-line {
					width: 1rpx;
					height: 120rpx;
					padding-right: 60rpx;
					opacity: 0;
				}
				&-total {
					position: absolute;
					width: 180rpx;
					height: 100%;
					flex-direction: column;
					justify-content: center;
					right: -20rpx;
					top: 0;
					// background: linear-gradient(to right, rgba(255,255,255,.8), #ffffff) no-repeat; /* 蓝色渐变 */
					// background-size: 62rpx 100%;
					background-color: #ffffff;
					z-index: 1;
					padding: 20rpx;
					box-sizing: border-box;
				}
				&-money {
					width: 100%;
					text-align: right;
					font-size: 28rpx;
					color: $primary-color;
				}
				&-count {
					height: 40rpx;
					font-size: 20rpx;
					text-align: center;
					justify-content: center;
					&-text {
						color: $primary-color;
					}
				}
				&-btns {
					flex-direction: column;
					align-self: flex-end;
					&-item {
						&.order-item-goods-btns-item {
							margin-top: 10rpx;
							font-size: 24rpx;
						}
					}
					&-item1 {
						color: #e1e1e1;
					}
					&-item2 {
						color: #f9ae3d;
					}
					&-item3 {
						color: #e3230e;
					}
				}
			}
			&-center {
				border-top: 1rpx solid #d6d7d9;
				border-bottom: 1rpx solid #d6d7d9;
			}
			&-more {
				padding: 0 20rpx;
				line-height: 1;
				margin-left: auto;
				&-icon {
					transition: all 0.3s;
				}
			}
			&-up {
				transform: rotate(180deg);
			}
			&-list {
				overflow: hidden;
				transition: all 0.3s;
				padding-left: 20rpx;
				.order-item-box {
					border-top: 1rpx solid rgba(214, 215, 217, 0.7);
					box-sizing: border-box;
				}
			}
			&-bottom {
				padding: 20rpx 0;
			}
			&-btns {
				justify-content: flex-end;
			}
			&-btn {
				width: 150rpx;
				height: 48rpx;
				padding: 0;
				margin: 0;
				font-size: 20rpx;
				justify-content: center;
				margin-left: 20rpx;
				border-radius: 24rpx;
				&-icon {
					width: 28rpx;
					height: 28rpx;
					margin-right: 10rpx;
				}
				&+.service {
					display: none;
				}
			}
		}
	}
</style>
